package com.google.code.sharecontent.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.google.code.sharecontent.dao.GroupDao;
import com.google.code.sharecontent.dao.UserDao;
import com.google.code.sharecontent.dao.UserGroupsDao;
import com.google.code.sharecontent.model.Group;
import com.google.code.sharecontent.model.User;
import com.google.code.sharecontent.model.UserGroups;

public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao {

	private UserGroupsDao userGroupsDao = null;
	private GroupDao groupDao = null;
	
	public UserDaoImpl(Connection conn) {
		super(conn);
	}

	@Override
	public User findByUsernamePassword(String username, String password) throws SQLException {
		ArrayList<User> list = this.list("USERNAME = '"+username+"' and PASSWORD='"+password+"'", "USERNAME");
		if (list != null && list.size()>0) {
			return list.get(0);
		}
		return null;
	}
	
	@Override
	protected String getTableName() {
		return "USERS";
	}
	
	@Override
	public User createByRow(ResultSet rs) throws SQLException {
		User user = new User();
		user.setId(rs.getInt("ID"));
		user.setUserName(rs.getString("USERNAME"));
		user.setFirstName(rs.getString("FIRSTNAME"));
		user.setLastName(rs.getString("LASTNAME"));
		user.setPassword(rs.getString("PASSWORD"));
		List<UserGroups> userGroups = getUserGroupsDao().list("USER_ID = "+user.getId(), null);
		if (userGroups != null && userGroups.size()>0) {
			for (UserGroups userGroup : userGroups) {
				Group group = getGroupsDao().get(userGroup.getGroupId());
				user.getGroups().add(group);
			}
		}
		return user;
	}

	private UserGroupsDao getUserGroupsDao() {
		if (this.userGroupsDao == null) {
			this.userGroupsDao = new UserGroupsDaoImpl(this.conn);
		}
		return this.userGroupsDao;
	}

	private GroupDao getGroupsDao() {
		if (this.groupDao == null) {
			this.groupDao = new GroupDaoImpl(this.conn);
		}
		return this.groupDao;
	}

	@Override
	protected PreparedStatement putPrepareStatement(PreparedStatement pStat,
			User status) throws SQLException {
		return pStat;
	}
	
}
